import React, { Component } from 'react'
import { Table, Button, Space, Input } from 'antd';
import { SearchOutlined } from '@ant-design/icons';

import { getUserList } from '../../api/user';

const { Column } = Table;

const sexFilters = [{ value: '0', text: '男' }, { value: '1', text: '女' }]

const statusFilters = [{ value: '0', text: '正常' }, { value: '1', text: '停用' }]

export default class TrapUser extends Component {

    state = {
        ds: [],
        pagination: {
            current: 1,
            pageSize: 5
        },
        sortParams: [{field: 'sex', order: 'ascend', multiple: 0}, {field: 'userName', order: 'ascend', multiple: 1}],
        queryParams: {}
    }

    componentDidMount() {
        this.getList()
    }

    getList = () => {
        let { current = 1, pageSize = 5 } = this.state.pagination
        let { queryParams, sortParams } = this.state
        getUserList({ current, pageSize, ...queryParams, sortParams }).then(res => {
            this.setState({ ds: res.rows })
            this.setState({ pagination: { ...this.state.pagination, total: res.total } })
        })
    }

    handleTableChange = (newPagination, filters, sorter) => {
        let { queryParams, sortParams } = this.state
        console.log('newPagination, filters, sorter', newPagination, filters, sorter)
        let newSortParams = sorter
        if (!Array.isArray(sorter)) {
            newSortParams = [sorter]
        }
        newSortParams = newSortParams.map(param => ({field: param.field, order: param.order, multiple: param.column.sorter.multiple}))
        // 设置分页和查询参数，并刷新列表
        this.setState({
            pagination: newPagination,
            queryParams: { ...queryParams, ...filters },
            sortParams: newSortParams
        }, () => {
            this.getList()
        })
    }

    handleSearch = (selectedKeys, confirm, dataIndex) => {
        confirm()
        let { queryParams } = this.state
        this.setState({
            queryParams: { ...queryParams, [dataIndex]: selectedKeys[0] }
        }, () => {
            this.getList()
        })
    }

    handleReset = ({clearFilters, dataIndex, setSelectedKeys}) => {
        clearFilters();
    }

    getFilterDropdown = ({ setSelectedKeys, selectedKeys, confirm, clearFilters }, dataIndex, name) => {
        return (
            <div
                style={{
                    padding: 8,
                }}
            >
                <Input
                    placeholder={`查询${name}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                    style={{
                        marginBottom: 8,
                        display: 'block',
                    }}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
                        icon={<SearchOutlined />}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        查询
                    </Button>
                    <Button
                        onClick={() => clearFilters && this.handleReset({clearFilters, dataIndex})}
                        size="small"
                        style={{
                            width: 90,
                        }}
                    >
                        重置
                    </Button>
                </Space>
            </div>
        )
    }

    filterIcon = (filtered) => (
        <SearchOutlined
            style={{
                color: filtered ? '#1890ff' : undefined,
            }}
        />
    )

    renderSexColumn = (text, record, index) => {
        return sexFilters.find(item => item.value === text)?.text
    }

    renderStatusColumn = (text, record, index) => {
        return statusFilters.find(item => item.value === text)?.text
    }

    renderDateColumn = (text, record, index) => {
        if (text) {
            if (text.indexOf('T') > 0) {
                text = text.replace('T', ' ')
            }
            if (text.indexOf('.') > 0) {
                text = text.split('.')[0]
            }
            return text
        }
    }

    getSorter = (dataIndex) => {
        let sortParam = this.state.sortParams.find(s => s.field === dataIndex);
        console.log('getSorter', dataIndex, sortParam)
        if (sortParam) {
            return {multiple: sortParam.multiple}
        }
        return false;
    }

    getOrder = (dataIndex) => {
        let sortParam = this.state.sortParams.find(s => s.field === dataIndex);
        if (sortParam) {
            return sortParam.order
        }
    }

    render() {
        let { ds, pagination } = this.state
        return (
            <div>
                <h1>用户管理</h1>
                <Table dataSource={ds} rowKey="userId" pagination={pagination} onChange={this.handleTableChange} onHeaderRow={this.handleTableHeaderClick}>
                    <Column title="ID" dataIndex="userId" key="userId" />
                    <Column title="用户名" dataIndex="userName" key="userName" filterDropdown={(props) => this.getFilterDropdown(props, 'userName', '用户名')} filterIcon={this.filterIcon} sorter={this.getSorter('userName')} defaultSortOrder={this.getOrder('userName')}/>
                    <Column title="昵称" dataIndex="nickName" key="nickName" filterDropdown={(props) => this.getFilterDropdown(props, 'nickName', '昵称')} filterIcon={this.filterIcon} />
                    <Column title="性别" dataIndex="sex" key="sex" filters={sexFilters} render={this.renderSexColumn} sorter={this.getSorter('sex')} defaultSortOrder={this.getOrder('sex')}/>
                    <Column title="邮箱" dataIndex="email" key="email" filterDropdown={(props) => this.getFilterDropdown(props, 'email', '邮箱')} filterIcon={this.filterIcon} />
                    <Column title="手机" dataIndex="phonenumber" key="phonenumber" filterDropdown={(props) => this.getFilterDropdown(props, 'phonenumber', '手机号')} filterIcon={this.filterIcon} />
                    <Column title="QQ号" dataIndex="qq" key="qq" filterDropdown={(props) => this.getFilterDropdown(props, 'qq', 'QQ')} filterIcon={this.filterIcon} />
                    <Column title="微信" dataIndex="wx" key="wx" filterDropdown={(props) => this.getFilterDropdown(props, 'wx', '微信')} filterIcon={this.filterIcon} />
                    <Column title="身份证" dataIndex="idCard" key="idCard" filterDropdown={(props) => this.getFilterDropdown(props, 'idCard', '身份证')} filterIcon={this.filterIcon} />
                    <Column title="状态" dataIndex="status" key="status" filters={statusFilters} render={this.renderStatusColumn} />
                    <Column title="创建人" dataIndex="createBy" key="createBy" />
                    <Column title="创建时间" dataIndex="createTime" key="createTime" render={this.renderDateColumn} />
                    <Column title="修改人" dataIndex="updateBy" key="updateBy" />
                    <Column title="修改时间" dataIndex="updateTime" key="updateTime" render={this.renderDateColumn} />
                </Table>
            </div>
        )
    }
}
